package com.epam.training.concurrency.first.task3;

import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Write data to buffer
 * 
 * @author Bogdan
 *
 */
class Writer implements Runnable {

	private Thread thread;
	private CircularBuffer buffer;

	public static final int THREAD_SLEEP = 1000;
	public static final int MAX_NUMBER = 65000;

	@Override
	public void run() {
		Random random = new Random();

		while (!thread.isInterrupted()) {

			int tmp = random.nextInt(MAX_NUMBER);
			System.out.println("Write number: " + tmp);
			buffer.store(tmp);
			try {
				Thread.sleep(random.nextInt(THREAD_SLEEP));
			} catch (InterruptedException e) {
				Logger.getLogger(CircularBuffer.class.getName()).log(
						Level.SEVERE, null, e);
			}
		}
	}

	Writer(CircularBuffer buffer) {
		this.buffer = buffer;
		thread = new Thread(this);
	}

	public void start() {
		thread.start();
	}

	public void stop() {
		thread.interrupt();
	}

}
